import React, { Component } from 'react'
import {localClass} from './style.scss'

export default class DropSelector extends Component {
    constructor(props){
        super();
        this.state = {
            dropperVisiable : false,
            index : props.defaultIndex,
        };
    }

    static defaultProps = {
        defaultValue : '请选择类型',
        defaultIndex : undefined,
        list : [],
        onItemClick : ({item, index})=>{
            console.log(item, index);
        }
    }

    componentDidMount() {
        document.addEventListener('click', this.documentClickHide , false);
    }

    componentWillUnmount = ()=>{
        this.documentClickHide = null;
    }

    documentClickHide = ()=>{
        this.setState({
            dropperVisiable : false,
        });
    }

    // 设置下拉框显示隐藏
    setDropperVisiable = (e)=>{
        this.setState(preveState => {
            return {
                dropperVisiable : !preveState.dropperVisiable
            }
        });
        e.nativeEvent.stopImmediatePropagation();
    }

    selectItem = ({item, index})=>{
        const {onItemClick} = this.props;
        this.setState({
            index
        });
        onItemClick({item, index});
    }
    
    render(){
        const {
            dropperVisiable,
            index,
        } = this.state;
        const {
            defaultValue,
            list,
        } = this.props;

        const selectedName = !isNaN(index) && list[index]? list[index].name : index === null? '全部' : defaultValue ;
        return (
            <span className={localClass + (dropperVisiable? ' open' : '')} onClick={this.setDropperVisiable}><i className={'selector-head' + (isNaN(index)? '' : ' selected')}>{selectedName}</i><a className="selector-icon"></a>
                <div className="selector-body">
                    <ul className="selector-list">
                        <li className="selector-list_item"><a onClick={()=>{ this.selectItem({index : null}); }}>全部</a></li>
                        {
                            list.map((item, index) => <li key={index} className="selector-list_item"><a onClick={()=>{ this.selectItem({item, index}); }}>{item.name}</a></li> )
                        }
                    </ul>
                </div>
            </span>
        )
    }
}